package com.music.mysongs.server

import java.io.*
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

object HelperServer {
    private const val port: Int = 7777
    private var myServer: ServerSocket? = null
    private var myExecutor: ExecutorService? = null

    @JvmStatic
    fun main(args: Array<String>) {
        server()
    }

    private fun server() {
        try {
            myServer = ServerSocket(port)
            myExecutor = Executors.newCachedThreadPool()
            val address: InetAddress = InetAddress.getLocalHost()
            println("server=$address")
            while (true) {
                myExecutor?.execute(SocketRun(myServer!!.accept()))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    class SocketRun(mSocket: Socket) : Runnable {
        private var read: BufferedReader? = null
        private var rSocket = mSocket

        init {
            try {
                read = BufferedReader(InputStreamReader(rSocket.getInputStream()))
                val msg = "嘿 ~ 有什么要问我的呀"
                sendMsg(msg)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        override fun run() {
            try {
                while (true) {
                    var msg: String
                    if (read?.readLine().also { msg = it.toString() } != null) {
                        when (msg) {
                            "我的功能" -> {
                                sendMsg("目前有5个，但是唠嗑未完善..更换主题未开发...嘘！")
                            }
                            "历史今日" -> {
                                sendMsg("就是历史上的今天啦")
                            }
                            "更换主题" -> {
                                sendMsg("还未开发，会研究滴，等等哈")
                            }
                            "拜拜" -> {
                                read?.close()
                                rSocket.close()
                                sendMsg(msg)
                                myServer!!.close()
                                break
                            }
                            else -> {
                                sendMsg("机器人听不懂人话...哼唧唧")
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        //为客户端发送信息
        private fun sendMsg(send: String) {
            println("sendMsg=$send")
            try {
                val pout = PrintWriter(
                    BufferedWriter(
                        OutputStreamWriter(rSocket.getOutputStream(), "UTF-8")
                    ), true
                )
                pout.println(send)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}